<template>
    <el-card shadow="never" class="data-overview">
        <div class="title_box">
            <p class="title">
                数据总览
                <el-tooltip effect="dark" placement="top-start">
                    <template #content>
                        <p v-for="(item, index) in targetArr" :key="index">{{ item?.label }}：{{ item?.tip }}</p>
                    </template>
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </p>
            <el-date-picker
                v-model="params.date"
                class="selectDate"
                type="daterange"
                :disabled-date="disabledDate"
                :editable="false"
                range-separator="~"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="changeDate"
                @calendar-change="calendarChange" />
        </div>
        <div class="data_box">
            <div v-for="(item, index) in targetArr" :key="index" class="data_item">
                <div class="data_title">
                    <span>{{ item?.label }}</span>
                </div>
                <p class="data_num">{{ item?.numSrt }}</p>
            </div>
        </div>
        <div class="trend_chart">
            <div class="title-box">
                <p>趋势图</p>
                <el-button @click="exportData">导出</el-button>
            </div>
            <div v-if="line_data.dateList.length" id="echarts" ref="myChartLineRef"></div>
            <div v-else v-loading="loading" class="none_data" element-loading-text="加载中...">
                <img class="no_img" src="@/assets/noData.png" alt="" />
                <div>暂无数据</div>
            </div>
        </div>
    </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, inject, onBeforeMount, computed, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { getDay, numFormat } from '@/utils/utils';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { overViewV1, trendChartV1, trendChartExportV1 } from '@/api/ecommerce/slaesStat.ts';

const echarts: any = inject('ec');

const route = useRoute();
const pickDay = ref();
const impose = ref(89);
/** 指标数据 */
const targetData = ref<any>({});
/** 折线图数据 */
const trendData = ref<any>([]);
/** 加载loading */
const loading = ref<boolean>(true);

const myChartLineRef = ref<any>(null);

/**
 * 接口参数
 *
 */
const params = reactive({
    retail_shop_id: route.query.shop_id,
    date: [getDay(-7), getDay(-1, true)] // 选择时间，默认是最近七天
});

/**
 * 折线图数据
 */
const line_data = ref({
    nameList: [],
    dateList: [],
    dataList: []
});

/**
 * 所有数据指标
 */
const targetArr = computed(() => [
    {
        label: '支付金额（元）',
        numSrt: numFormat(targetData.value['pay_amount']),
        tip: '筛选时间内，支付成功的订单总金额，包含运费，支付后退款，支付金额不扣减。'
    },
    {
        label: '支付订单数',
        numSrt: numFormat(targetData.value['pay_num']),
        tip: '筛选时间内，支付成功的订单总数，支付后退款，支付订单数不扣减。'
    },
    {
        label: '支付用户数',
        numSrt: numFormat(targetData.value['pay_user_num']),
        tip: '筛选时间内，支付成功的用户总数，一个用户多次支付记为一个。'
    },
    {
        label: '客单价（元）',
        numSrt: numFormat(targetData.value['guest_unit_price']),
        tip: '筛选时间内，平均每个用户的支付金额，客单价=支付金额/支付用户数。'
    },
    {
        label: '笔单价（元）',
        numSrt: numFormat(targetData.value['unit_price']),
        tip: '筛选时间内，平均每笔订单的支付金额，笔单价=支付金额/支付订单数。'
    },
    {
        label: '复购用户数',
        numSrt: numFormat(targetData.value['repurchase_num']),
        tip: '筛选时间内，支付成功两次及以上订单的用户总数。'
    },
    {
        label: '复购率',
        numSrt: numFormat(targetData.value['repurchase_rate']) + '%',
        tip: '筛选时间内，复购用户数/支付用户数。'
    },
    {
        label: '新增用户数',
        numSrt: numFormat(targetData.value['new_user_num']),
        tip: '筛选时间内，新增用户的数量。'
    }
]);

// 默认选中
const defaultSelect = (data: any) => {
    return Object.keys(data).reduce((ret: any, key: string) => {
        if (['支付金额（元）', '退款金额（元）'].includes(data[key])) {
            ret[data[key]] = true;
        } else {
            ret[data[key]] = false;
        }
        return ret;
    }, {});
};
// 折线图配置项
const getEchartsLine = () => {
    const myChartLine = echarts?.init(myChartLineRef.value);
    const option = {
        color: [
            '#FF9228',
            '#2EB5E3',
            '#4AD983',
            '#FF724D',
            '#ED1F45',
            '#FFB323',
            '#4A7EE6',
            '#8C5FBC',
            '#30CBA8',
            '#FDD300',
            '#CE31CE',
            '#5AE2E0',
            '#668EFF'
        ],
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            x: 'center',
            y: 'bottom',
            padding: [0, 0, 30, 0],
            data: line_data.value.nameList,
            selected: defaultSelect(line_data.value.nameList)
        },
        grid: {
            top: 30,
            bottom: 80,
            left: 32,
            right: 40,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: line_data.value.dateList,
            boundaryGap: false,
            offset: 3
        },
        yAxis: {
            type: 'value',
            name: '',
            nameGap: 10, // y轴name与横纵坐标轴线的间距
            nameTextStyle: {
                padding: [0, 35, 10, 0] // 加上padding可以调整其位置
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#969696'
            },
            splitLine: {
                lineStyle: {
                    type: 'line',
                    color: '#e8e8e8' // 分割线颜色
                }
            }
        },
        series: line_data.value.dataList
    };
    myChartLine.setOption(option);
    window.addEventListener('resize', function () {
        if (myChartLine) {
            myChartLine.resize();
        }
    });
};

/**
 * 选择时间做多支持选择90天的数据
 */
const disabledDate = (time: any) => {
    if (!pickDay.value) {
        return time.getTime() > Date.now() - 3600 * 1000 * 24;
    }
    const con1 = new Date(pickDay.value).getTime() - 89 * 24 * 60 * 60 * 1000;
    const con2 = new Date(pickDay.value).getTime() + 89 * 24 * 60 * 60 * 1000;
    const con3 = time.getTime() > Date.now() - 3600 * 1000 * 24;
    return con3 ? con3 : time.getTime() < con1 || time.getTime() > con2;
};

const calendarChange = (val: Date[]) => {
    const [pointDay] = val;
    pickDay.value = pointDay;
};

/**
 * 获取数据指标
 */
const initData = async () => {
    loading.value = true;
    const res = await overViewV1(params).catch(() => {
        loading.value = false;
    });
    if (res) {
        loading.value = false;
        targetData.value = res;
    }
};

/**
 * 获取趋势图数据
 */
const initTrendChartData = async () => {
    const res = await trendChartV1(params).catch(() => {
        loading.value = false;
    });
    if (res) {
        loading.value = false;
        trendData.value = res;
    }
};

/**
 * 变更时间
 */
const changeDate = (val: any = []) => {
    if (!val || !val.length) {
        pickDay.value = '';
        return;
    }
    const start = val[0] + ' ' + '00:00:00';
    const end = val[1] + ' ' + '23:59:59';
    params.date = [start, end];
    initData();
    initTrendChartData();
};
/**
 * 导出异步任务
 */
const exportData = async () => {
    const res = await trendChartExportV1(params);
    ShowTaskMessage('导出异步任务创建成功');
};

watch(
    () => trendData.value,
    val => {
        line_data.value = val || [];
        line_data.value.dataList = val.nameList.map((item: any, index: any) => {
            return {
                name: item,
                type: 'line',
                smooth: true,
                data: val.dataList[index],
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#F8DCD1' },
                            { offset: 0.5, color: '#FDF8F6' },
                            { offset: 1, color: '#FFFAF9' }
                        ])
                    }
                }
            };
        });
        nextTick(() => {
            getEchartsLine();
        });
    }
);

onBeforeMount(() => {
    initData();
    initTrendChartData();
});
</script>

<style lang="scss" scoped>
.data-overview {
    :deep(.el-card__body) {
        padding: 0;
    }
}

.title_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 12px 24px;
    border-bottom: 1px solid #eaeaea;

    .title {
        display: flex;
        align-items: center;
        line-height: 16px;

        .box-icon {
            color: #ccc;
            margin-left: 4px;
        }
    }

    :deep(.selectDate) {
        max-width: 311px;
    }
}

.data_box {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    grid-row-gap: 32px;
    align-items: center;
    padding: 0 24px;
    margin: 36px 0 46px;

    .data_item {
        .data_title {
            font-size: 14px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: #666;
            line-height: 20px;
        }

        .data_num {
            margin-top: 8px;
            font-size: 24px;
            font-family: HelveticaNeue-Medium, HelveticaNeue;
            font-weight: 500;
            color: #33302d;
            line-height: 24px;
        }
    }
}

.trend_chart {
    padding: 0 24px;

    .title-box {
        display: flex;
        align-items: center;
        justify-content: space-between;

        p {
            font-size: 16px;
            font-weight: 500;
            color: #33302d;
            display: flex;
            align-items: center;

            &::before {
                display: inline-block;
                content: '';
                width: 3px;
                height: 16px;
                margin-right: 6px;
                background: #ff6b00;
                border-radius: 2px;
            }
        }
    }

    #echarts {
        display: flex;
        justify-content: center;
        height: 400px;
    }

    .none_data {
        margin: 100px 0;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        color: #909399;

        img {
            transform: translateX(15%);
        }
    }
}
</style>
